<?php include_once( "_db.php" ); //Database ?>
<?php include_once( "funcdef.php" ); //Functions Definition ?>
<?php include_once( "header.php" ); //Header ?>
<?php include_once( "footer.php" ); //Footer ?>
<?php
//include page header
header_template("Product", $_SERVER['PHP_SELF'], "icon-tags");

//db OBJECT invoked!
$db = new DATABASE();
?>
      <div class="row">
        <div class="span6">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  //Submit button for Create
  $button_submit_name  = "create-product";
  $button_submit_value = "Create";
  //Hidden product id
  $hidden_product_id = "";
  //Product for Create
  $res = array();
  if (isset($_GET["action"]) && isset($_GET["prod_id"])) {
    if ($_GET["action"] == "edit") {
      //Product for Edit
      //construct SELECT query
      $conds = array();
      $conds[] = array(0); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($_GET["prod_id"]); //$param_key;
      $query = $db->db_select("product", NULL, $conds);
      //execute SELECT query
      $result = $db->database->query($query);
      //result SELECT query
      $res = $result->fetchAll(SQLITE_ASSOC);
      //Submit button for Edit
      $button_submit_name  = "edit-product";
      $button_submit_value = "Edit";
      //Hidden product id
      $hidden_product_id = "<input type='hidden' name='product_id' value='".$res[0]['product_id']."' />";
    }
  }
//Product Form
?>
          <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="application/x-www-form-urlencoded" class="form-horizontal">
            <?php echo $hidden_product_id."\n"; ?>
            <fieldset>
              <div class="control-group">
                <label class="control-label" for="product_name">Product</label>
                <div class="controls">
                  <input type="text" class="input-xlarge" id="product_name" name="product_name" value="<?php echo $res[0]['product_name']; ?>">
                </div>
              </div>
              <div class="control-group">
                <label class="control-label" for="product_price">Price</label>
                <div class="controls">
                  <div class="input-prepend">
                  <span class="add-on">MYR</span><input type="text" class="input-mini" id="product_price" name="product_price" value="<?php echo $res[0]['product_price']; ?>">
                  </div>
                </div>
              </div>
              <div class="control-group">
                <label class="control-label" for="product_quantity">Quantity</label>
                <div class="controls">
                  <input type="text" class="input-mini" id="product_quantity" name="product_quantity" value="<?php echo $res[0]['product_quantity']; ?>">
                </div>
              </div>
              <div class="control-group">
                <label class="control-label" for="product_description">Description</label>
                <div class="controls">
                  <textarea class="input-xlarge" id="product_description" name="product_description"rows="3"><?php echo $res[0]['product_description']; ?></textarea>
                </div>
              </div>
              <div class="form-actions">
                <input type="submit" name="<?php echo $button_submit_name; ?>" value="<?php echo $button_submit_value; ?>" class="btn btn-info" />
              </div>
            </fieldset>
          </form>
<?php
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
  //Create Product
  if ($_POST['create-product'] == "Create") {
    //Form field check NG
    if ($_POST["product_name"] == "") {
      printAlert("error", "Oh snap!", "Product field is empty.", $_SERVER['PHP_SELF']);
    } elseif ($_POST["product_price"] == "") {
      printAlert("error", "Oh snap!", "Price field is empty.", $_SERVER['PHP_SELF']);
    } elseif (!is_numeric($_POST["product_price"])) {
      printAlert("error", "Oh snap!", "Price is not numeric.", $_SERVER['PHP_SELF']);
    } elseif ($_POST["product_quantity"] == "") {
      printAlert("error", "Oh snap!", "Quantity field is empty.", $_SERVER['PHP_SELF']);
    } elseif (!is_numeric($_POST["product_quantity"])) {
      printAlert("error", "Oh snap!", "Quantity is not numeric.", $_SERVER['PHP_SELF']);
    } else {//Form field check OK
      //construct INSERT query
      $params = array();
      $params[] = array(1, 2, 3, 4); //$param_col;
      $params[] = array($_POST["product_name"], $_POST["product_description"], $_POST["product_quantity"], $_POST["product_price"]); //$param_key;
      $query = $db->db_insert("product", $params);
      //execute INSERT query
      $result = $db->database->query($query);
      //Add product NG
      if ($result == FALSE) {
        printAlert("error", "Oh snap!", "Cannot create Product '".$_POST["product_name"]."'.", $_SERVER['PHP_SELF']);
      } else {//Add product OK
        //INSERT SUCCEED!!!
        printAlert("success", "Well done!", "Product '".$_POST["product_name"]."' successfully created.", $_SERVER['PHP_SELF']);
      }
    }
  }
  //Edit Product
  if ($_POST['edit-product'] == "Edit") {
    //Form field check NG
    if ($_POST["product_name"] == "") {
      printAlert("error", "Oh snap!", "Product field is empty.", $_SERVER['PHP_SELF']);
    } elseif ($_POST["product_price"] == "") {
      printAlert("error", "Oh snap!", "Price field is empty.", $_SERVER['PHP_SELF']);
    } elseif (!is_numeric($_POST["product_price"])) {
      printAlert("error", "Oh snap!", "Price is not numeric.", $_SERVER['PHP_SELF']);
    } elseif ($_POST["product_quantity"] == "") {
      printAlert("error", "Oh snap!", "Quantity field is empty.", $_SERVER['PHP_SELF']);
    } elseif (!is_numeric($_POST["product_quantity"])) {
      printAlert("error", "Oh snap!", "Quantity is not numeric.", $_SERVER['PHP_SELF']);
    } else {//Form field check OK
      //construct UPDATE query
      $params = array();
      $params[] = array(1, 2, 3, 4); //$param_col;
      $params[] = array($_POST["product_name"], $_POST["product_description"], $_POST["product_quantity"], $_POST["product_price"]); //$param_key;
      $conds = array();
      $conds[] = array(0); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($_POST["product_id"]); //$param_key;
      $query = $db->db_update("product", $params, $conds);
      //execute UPDATE query
      $result = $db->database->query($query);
      //Edit product NG
      if ($result == FALSE) {
        printAlert("error", "Oh snap!", "Cannot edit Product '".$_POST["product_name"]."'.", $_SERVER['PHP_SELF']);
      } else {//Edit product OK
        //UPDATE SUCCEED!!!
        printAlert("success", "Well done!", "Product '".$_POST["product_name"]."' successfully edited.", $_SERVER['PHP_SELF']);
      }
    }
  }
} else {
  $error_msg = "This script only works with GET and POST requests.";
  printAlert("error", "Oh snap!", $error_msg, $_SERVER['PHP_SELF']);
}

//Delete Product
if (isset($_GET["action"]) && isset($_GET["prod_id"])) {
  if ($_GET["action"] == "delete") {

    //construct SELECT query
    $conds = array();
    $conds[] = array(0); //$param_col;
    $conds[] = array(0); //$param_op;
    $conds[] = array($_GET["prod_id"]); //$param_key;
    $query = $db->db_select("product", NULL, $conds);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $resProd = $result->fetchAll(SQLITE_ASSOC);

    //construct SELECT query
    $conds = array();
    $conds[] = array(1); //$param_col;
    $conds[] = array(0); //$param_op;
    $conds[] = array($_GET["prod_id"]); //$param_key;
    $query = $db->db_select("product2deal", NULL, $conds);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $resProd2Deal = $result->fetchAll(SQLITE_ASSOC);

    //ID check OK
    if (!empty($resProd)) {
      //CHECK FOR product2deal
      //check product to deal link OK
      if (empty($resProd2Deal)) {
        //construct SELECT query
        $conds = array();
        $conds[] = array(0); //$param_col;
        $conds[] = array(0); //$param_op;
        $conds[] = array($_GET["prod_id"]); //$param_key;
        $query = $db->db_select("product", NULL, $conds);
        //execute SELECT query
        $result = $db->database->query($query);
        //result SELECT query
        $res = $result->fetchAll(SQLITE_ASSOC);
        //construct DELETE query
        $query = $db->db_delete("product", $conds);
        //execute DELETE query
        $result = $db->database->query($query);
        //delete product NG
        if ($result == FALSE) {
          printAlert("error", "Oh snap!", "Cannot delete ".$res[0]['product_name'], $_SERVER['PHP_SELF']);
        } else {//delete product OK
          //DELETE SUCCEED!!!
          printAlert("success", "Well done!", $res[0]['product_name']." successfully deleted", $_SERVER['PHP_SELF']);

          //CHECK FOR category2product
          //construct DELETE params
          $conds = array();
          $conds[] = array(2); //$param_col;
          $conds[] = array(0); //$param_op;
          $conds[] = array($_GET["prod_id"]); //$param_key;
          //construct DELETE query
          $query = $db->db_delete("category2product", $conds);
          //execute DELETE query
          $result = $db->database->query($query);
          /*
          if ($result == FALSE) {
            printAlert("error", "Oh snap!", "Cannot delete ".$res[0]['product_name'], $_SERVER['PHP_SELF']);
          } else {//delete product OK
            //DELETE SUCCEED!!!
            printAlert("success", "Well done!", $res[0]['product_name']." successfully deleted", $_SERVER['PHP_SELF']);
          }
          */
          //CHECK FOR picture2product
          //construct DELETE query
          $query = $db->db_delete("picture2product", $conds);
          //execute DELETE query
          $result = $db->database->query($query);
          /*
          if ($result == FALSE) {
            printAlert("error", "Oh snap!", "Cannot delete ".$res[0]['product_name'], $_SERVER['PHP_SELF']);
          } else {//delete product OK
            //DELETE SUCCEED!!!
            printAlert("success", "Well done!", $res[0]['product_name']." successfully deleted", $_SERVER['PHP_SELF']);
          }
          */
        }
      } else {//check product to deal link NG
        printAlert("error", "Oh snap!", "Product is link to deal.", $_SERVER['PHP_SELF']);
      }
    } else {//ID check NG
      printAlert("error", "Oh snap!", "Product ID not exist.", $_SERVER['PHP_SELF']);
    }
  }
}

//Pagination
//set number of prod / page
$prodPerPage = 10;
//initialize current page
$curPage = 0;
//set first page
$firstPage = 1;
//initialize last page
$cols = "count";
$conds = NULL;
$query = $db->db_select("product", $cols, $conds);
//$query = "SELECT count(*) FROM product";
$rowCount = $db->database->query($query);
$rowCount = $rowCount->fetchAll(SQLITE_NUM);
$rowCount = intval($rowCount[0][0]);
$remainder = intval($rowCount % $prodPerPage);
$lastPage = intval($rowCount / $prodPerPage);
//set current page
if ((isset($_GET["page"])) && (is_numeric($_GET["page"]))) {
  $curPage = intval($_GET["page"]);
} else {
  $curPage = $firstPage;
}
//set last page
if ($remainder > 0) {
  $lastPage++;
}
if ($lastPage > 1) { //pagination start
?>
          <ul class="pager">
<?php
  if ($curPage != $firstPage) {
    $pager_prev_state = " active";
    $pager_prev_href  = " href=\"".$_SERVER['PHP_SELF']."?page=".($curPage-1)."\"";
  } else {
    $pager_prev_state = " disabled";
    $pager_prev_href  = "";
  }

  if ($curPage != $lastPage) {
    $pager_next_state = " active";
    $pager_next_href  = " href=\"".$_SERVER['PHP_SELF']."?page=".($curPage+1)."\"";
  } else {
    $pager_next_state = " disabled";
    $pager_next_href  = "";
  }
?>
            <li class="previous <?php echo $pager_prev_state; ?>">
              <a<?php echo $pager_prev_href; ?>>&larr; Prev</a>
            </li>
            <li class="next <?php echo $pager_next_state; ?>">
              <a<?php echo $pager_next_href; ?>>Next &rarr;</a>
            </li>
          </ul>
          <center>
            <p><span class="label label-info">Page <?php echo $curPage; ?>/<?php echo $lastPage; ?></span></p>
          </center>
<?php } //pagination end ?>
          <table class="table table-condensed table-striped">
            <thead>
              <tr>
                <th>Product</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>&nbsp;</th>
              </tr>
            </thead>
            <tbody>
<?php
//construct SELECT query
$query = $db->db_select("product", NULL, NULL);
//execute SELECT query
$result = $db->database->query($query." ORDER BY product_id DESC LIMIT ".(($curPage-1)*$prodPerPage).", ".$prodPerPage);
/*$result = $db->database->query($query." ORDER BY product_id DESC");*/
//result SELECT query
$products = $result->fetchAll(SQLITE_ASSOC);
//List product(s)
//Product(s) existence OK
if (!empty($products)) {
  //loop trough all product(s)
  foreach ($products as $prod) {
    $query = "SELECT category.category_name FROM category2product, category "
           . "WHERE category2product.product_id = "
           . "'".$prod['product_id']."' "
           . "AND category2product.category_id = category.category_id";
    $result = $db->database->query($query);
    $categories = $result->fetchAll(SQLITE_ASSOC);

    $cat_str = "";
    foreach ($categories as $key => $cat) {
      if ($key != 0) {
        $cat_str .= ", ";
        $cat_str .= $cat['category.category_name'];
      } else {
        $cat_str .= $cat['category.category_name'];
      }
    }
    $product_frontage_href = "product_frontage.php?prod_id=".$prod['product_id'];
    $product_edit_href = $_SERVER['PHP_SELF']."?action=edit&prod_id=".$prod['product_id'];

    //Get Product2Deal
    $cols = NULL;
    $conds = array();
    $conds[] = array(1);
    $conds[] = array(0);
    $conds[] = array($prod['product_id']);
    $query = $db->db_select("product2deal", $cols, $conds);
    $result = $db->database->query($query);
    $tmpProd2Deal = $result->fetchAll(SQLITE_ASSOC);
    //CHECK FOR product2deal
    if (!empty($tmpProd2Deal)) {
      $product_delete_href = "";
      $prod_delete_lnk_state = " disabled";
    } else {
      $product_delete_href = $_SERVER['PHP_SELF']."?action=delete&prod_id=".$prod['product_id'];
      $prod_delete_lnk_state = "";
    }
?>
              <tr>
                <td><?php echo $prod['product_name']; ?></td>
                <td>MYR <?php echo $prod['product_price']; ?></td>
                <td><?php echo $prod['product_quantity']; ?></td>
                <td>
                  <a class="btn btn-default btn-mini" rel="tooltip" title="<?php echo $prod['product_description']; ?>">Desc</a>
                  <a class="btn btn-default btn-mini" rel="tooltip" title="<?php echo $cat_str; ?>">Cat</a>
                  <a class="btn btn-success btn-mini" href="<?php echo $product_frontage_href; ?>">Frontage</a>
                  <a class="btn btn-success btn-mini" href="<?php echo $product_edit_href; ?>">Edit</a>
                  <a class="btn btn-danger btn-mini<?php echo $prod_delete_lnk_state; ?>" href="<?php echo $product_delete_href; ?>">Delete</a>
                </td>
              </tr>
<?php
  }
}
?>
            </tbody>
          </table>
        </div>
      </div>
<?php
//include page footer
footer_template();
?>
